<template>
  <div class="comment-container">
    <h2>商品评论</h2>
    <div v-if="loading">加载中...</div>
    <div v-else>
      <div class="comment-card-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-card">
          <img :src="comment.img || `/src/assets/tea/longjing.jpg`" alt="商品图片" />
          <div class="comment-info">
            <div class="comment-user"><strong>{{ comment.username }}</strong></div>
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-time">时间：{{ comment.createdAt }}</div>
          </div>
        </div>
      </div>
      <div v-if="comments.length === 0">暂无评论</div>
    </div>
    <form @submit.prevent="submitComment" v-if="token">
      <textarea v-model="content" placeholder="请输入评论..." required></textarea>
      <button type="submit">发表评论</button>
    </form>
    <div v-else>请登录后发表评论</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from '../api/axios';

const comments = ref<any[]>([]);
const content = ref('');
const loading = ref(false);
const token = localStorage.getItem('token');

const fetchComments = async () => {
  loading.value = true;
  try {
    // 假设后端有 /comment 接口
    const res = await axios.get('/comment');
    comments.value = res.data;
  } catch {
    comments.value = [];
  } finally {
    loading.value = false;
  }
};

const submitComment = async () => {
  if (!content.value) return;
  try {
    await axios.post('/comment', { content: content.value });
    content.value = '';
    fetchComments();
  } catch {}
};

onMounted(fetchComments);
</script>

<style scoped>
  .comment-container {
    max-width: 1200px;
    margin: 40px auto;
    padding: 32px;
    background: #fffbe6;
    border-radius: 16px;
    box-shadow: 0 4px 24px #ffe7ba;
    min-height: 480px;
  }
.comment-card-list {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  justify-content: flex-start;
}
.comment-card {
  display: flex;
  align-items: center;
  width: 400px;
  background: #fffbe6;
  border-radius: 12px;
  box-shadow: 0 2px 8px #ffd591;
  padding: 16px;
  margin-bottom: 16px;
}
.comment-card img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 16px;
}
.comment-info {
  flex: 1;
}
.comment-user {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 4px;
}
.comment-content {
  font-size: 14px;
  margin-bottom: 4px;
}
.comment-time {
  font-size: 13px;
  color: #888;
}
textarea {
  width: 100%;
  min-height: 60px;
  margin: 12px 0;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ccc;
}
</style>
